<template>
  <view class="hospital-edit-container">
    <view class="page-header">
      <text class="page-title">编辑医院</text>
      <text class="page-subtitle">修改医院信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">医院名称</text>
          <uni-easyinput 
            v-model="formData.hospital_name"
            placeholder="请输入医院名称"
            :maxlength="100"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.hospital_name" class="error-text">{{ errors.hospital_name }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">地址</text>
          <uni-easyinput 
            v-model="formData.address"
            placeholder="请输入医院地址"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.address" class="error-text">{{ errors.address }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">电话</text>
          <uni-easyinput 
            v-model="formData.phone"
            type="tel"
            placeholder="请输入联系电话"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">医院介绍</text>
          <textarea 
            v-model="formData.introduction" 
            class="form-textarea" 
            placeholder="请输入医院介绍"
            maxlength="1000"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">图片信息</text>
        
        <view class="form-item">
          <text class="form-label">医院Logo</text>
          <uni-file-picker 
            v-model="logoFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handleLogoSelect"
            @delete="handleLogoDelete"
          />
        </view>

      </view>

      <view class="form-section">
        <text class="section-title">营业信息</text>
        
        <view class="form-item">
          <text class="form-label">工作开始时间</text>
          <picker mode="time" :value="formData.working_hours_start" @change="onStartTimeChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.working_hours_start || '请选择开始时间' }}</text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">工作结束时间</text>
          <picker mode="time" :value="formData.working_hours_end" @change="onEndTimeChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.working_hours_end || '请选择结束时间' }}</text>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="form-label">每周休息日</text>
          <view class="checkbox-group">
            <label v-for="(day, index) in weekDays" :key="index" class="checkbox-item">
              <checkbox 
                :value="day.value" 
                :checked="formData.closed_days.includes(day.value)"
                @tap="toggleClosedDay(day.value)"
                color="#007aff"
              />
              <text class="checkbox-text">{{ day.label }}</text>
            </label>
          </view>
        </view>

        <view class="form-item">
          <text class="form-label">法定节假日</text>
          <radio-group @change="onHolidayClosedChange" class="radio-group">
            <label class="radio-item">
              <radio 
                value="true" 
                :checked="formData.holiday_closed === true"
                color="#007aff"
              />
              <text class="radio-text">节假日休息</text>
            </label>
            <label class="radio-item">
              <radio 
                value="false" 
                :checked="formData.holiday_closed === false"
                color="#007aff"
              />
              <text class="radio-text">节假日营业</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">停车信息</text>
          <uni-easyinput 
            v-model="formData.parking_info"
            placeholder="请输入停车信息"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">公交信息</text>
          <uni-easyinput 
            v-model="formData.public_transport"
            placeholder="请输入公交信息"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">证照信息</text>
        
        <view class="form-item">
          <text class="form-label">营业执照号</text>
          <uni-easyinput 
            v-model="formData.business_license"
            placeholder="请输入营业执照号"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">医疗许可证号</text>
          <uni-easyinput 
            v-model="formData.medical_license"
            placeholder="请输入医疗许可证号"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const hospitalId = ref('')
const logoFileList = ref([])
const originalLogoUrl = ref('')
const originalLogoData = ref(null) // 保存原始logo对象

const formData = reactive({
  hospital_name: '',
  address: '',
  phone: '',
  introduction: '',
  logo: '',
  working_hours_start: '',
  working_hours_end: '',
  closed_days: [],
  parking_info: '',
  public_transport: '',
  business_license: '',
  medical_license: ''
})

const errors = reactive({
  hospital_name: '',
  address: '',
  phone: ''
})

const weekDays = [
  { value: '周一', label: '周一' },
  { value: '周二', label: '周二' },
  { value: '周三', label: '周三' },
  { value: '周四', label: '周四' },
  { value: '周五', label: '周五' },
  { value: '周六', label: '周六' },
  { value: '周日', label: '周日' }
]

// 星期中英文映射
const weekDayMap = {
  'Monday': '周一',
  'Tuesday': '周二',
  'Wednesday': '周三',
  'Thursday': '周四',
  'Friday': '周五',
  'Saturday': '周六',
  'Sunday': '周日'
}

// 转换英文星期为中文
function convertClosedDays(days) {
  if (!days || !Array.isArray(days)) return []
  
  // 转换英文为中文
  const converted = days.map(day => weekDayMap[day] || day)
  // 去重
  return [...new Set(converted)]
}

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  hospitalId.value = currentPage.options.id || ''
  
  if (!hospitalId.value) {
    uni.showToast({ title: '缺少医院ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/hospitals/list' })
    }, 1500)
    return
  }
  
  await loadHospitalData()
  pageLoading.value = false
})

function getImageUrl(imageData) {
  if (!imageData) return ''
  // 如果是字符串，直接返回
  if (typeof imageData === 'string') return imageData
  // 如果是对象，尝试提取url属性
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  // 如果是数组，取第一个元素的url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

async function loadHospitalData() {
  try {
    // 调用云对象方法获取医院信息
    const hospitalsObj = uniCloud.importObject('dh-hospitals')
    const result = await hospitalsObj.getHospital(hospitalId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      
      // 保存原始图片数据（file对象）
      originalLogoData.value = data.logo || null
      
      // 提取图片URL用于显示
      const logoUrl = getImageUrl(data.logo)
      
      Object.assign(formData, {
        hospital_name: data.hospital_name || '',
        address: data.address || '',
        phone: data.phone || '',
        introduction: data.introduction || '',
        logo: logoUrl,
        working_hours_start: data.working_hours_start || '',
        working_hours_end: data.working_hours_end || '',
        closed_days: convertClosedDays(data.closed_days),
        holiday_closed: data.holiday_closed !== undefined ? data.holiday_closed : true,
        parking_info: data.parking_info || '',
        public_transport: data.public_transport || '',
        business_license: data.business_license || '',
        medical_license: data.medical_license || ''
      })
      
      if (logoUrl) {
        originalLogoUrl.value = logoUrl
        logoFileList.value = [{ url: logoUrl, name: 'Logo' }]
      }
    } else {
      throw new Error(result.message || '医院不存在')
    }
  } catch (err) {
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/hospitals/list' })
    }, 1500)
  }
}

function onStartTimeChange(e) {
  formData.working_hours_start = e.detail.value
}

function onEndTimeChange(e) {
  formData.working_hours_end = e.detail.value
}

function toggleClosedDay(value) {
  const index = formData.closed_days.indexOf(value)
  if (index > -1) {
    formData.closed_days.splice(index, 1)
  } else {
    formData.closed_days.push(value)
  }
}

function onHolidayClosedChange(e) {
  formData.holiday_closed = e.detail.value === 'true'
}

function handleLogoSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    logoFileList.value = e.tempFiles
  }
}

function handleLogoDelete(e) {
  logoFileList.value = []
}

async function uploadImageToCloud(file, folder) {
  try {
    const uploadResult = await uniCloud.uploadFile({
      filePath: file.path,
      cloudPath: `${folder}/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.name.split('.').pop()}`
    })
    // 返回符合数据库schema的file对象结构
    return {
      bsonType: 'file',
      fileMediaType: 'image',
      url: uploadResult.fileID
    }
  } catch (err) {
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.hospital_name || formData.hospital_name.trim().length === 0) {
    errors.hospital_name = '请输入医院名称'
    isValid = false
  } else {
    errors.hospital_name = ''
  }
  
  if (!formData.address || formData.address.trim().length === 0) {
    errors.address = '请输入医院地址'
    isValid = false
  } else {
    errors.address = ''
  }
  
  if (!formData.phone || formData.phone.trim().length === 0) {
    errors.phone = '请输入联系电话'
    isValid = false
  } else {
    errors.phone = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  let submitData = null // 定义在外部以便catch块访问
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    // 处理Logo
    let logoData = null
    const hasNewLogo = logoFileList.value && logoFileList.value.length > 0 && logoFileList.value[0].path && !logoFileList.value[0].url
    if (hasNewLogo) {
      uni.showLoading({ title: '上传Logo中...' })
      logoData = await uploadImageToCloud(logoFileList.value[0], 'hospitals/logos')
    } else if (originalLogoData.value) {
      // 保持原始file对象
      logoData = originalLogoData.value
    }
    
    // 转换reactive对象为普通对象
    if (logoData && typeof logoData === 'object') {
      logoData = JSON.parse(JSON.stringify(logoData))
    }
    
    const db = uniCloud.database()
    const dbCmd = db.command
    
    submitData = {
      hospital_name: formData.hospital_name || '',
      address: formData.address || '',
      phone: formData.phone || '',
      introduction: formData.introduction || '',
      working_hours_start: formData.working_hours_start || '',
      working_hours_end: formData.working_hours_end || '',
      closed_days: formData.closed_days || [],
      holiday_closed: formData.holiday_closed,
      parking_info: formData.parking_info || '',
      public_transport: formData.public_transport || '',
      business_license: formData.business_license || '',
      medical_license: formData.medical_license || '',
      update_time: Date.now()
    }
    
    // 如果有logo数据，添加logo字段；否则移除该字段
    if (logoData) {
      submitData.logo = logoData
    } else {
      submitData.logo = dbCmd.remove()
    }
    
    // 调用云对象方法更新医院信息
    const hospitalsObj = uniCloud.importObject('dh-hospitals')
    const result = await hospitalsObj.updateHospital(hospitalId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/hospitals/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/hospitals/list' })
}
</script>

<style lang="scss" scoped>
.hospital-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
  min-width: 140rpx;
}

.checkbox-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.radio-group {
  display: flex;
  gap: 24rpx;
  flex-wrap: wrap;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
  min-width: 180rpx;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
